﻿var allServices = [];
var bouquetSelected;
var bouquet;
var currChannel;
var servicesLoaded = false;
var connected;
var settingID;
var connAttempts = 0;

$(function () {
    $.ajaxSetup({
        // Disable caching of AJAX responses
        cache: false
    });

    $(document).bind('pageinit', function (event, data) {

        CheckConnection();

        if (SettingsHelper.SettingsLoded() == false) {
            document.addEventListener("deviceready", onDeviceReady, false);
            SettingsHelper.SettingsLoded(true);
        }

        window.console = {
            log: function (str) { window.external.Notify(str); }
        };

        // output errors to console log
        window.onerror = function (e) {
            console.log("window.onerror ::" + JSON.stringify(e));
        };
        
        $.get(getPath(uri.currService, ''), function (current) {
            currChannel = current;
            //$.get(uri.receiver + "/cgi-bin/getServices?ref=1:15:fffffffe:12:ffffffff:0:0:0:0:0:", function (data) {
            //    getAllServices(current, data);
            //    servicesLoaded = true;
            //});
        });
    });

    // Cordova is ready //
    function onDeviceReady() {
        document.addEventListener("pause", onPause, false);
        document.addEventListener("resume", onResume, false);

        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccessR, fail);        
    };


    $('#bouquets').bind('pagebeforeshow', function (event, data) {
        try {
           // alert(window['localStorage'] !== null);

            //var r = localStorage.setItem('a', 'b');
            //var t = typeof (localStorage) == 'undefined';
            //alert(t);

            $.get(getPath(uri.getServices, "4097:7:0:6:0:0:0:0:0:0:"), function (data) {
                DisplayBouquets(data);
            });
        }
        catch (err) { alert(JSON.stringify(err)); }
    });

    $('#channels').bind('pagebeforeshow', function (e, data) {
        try {
            //console.log('sads ' + JSON.stringify(bouquet))
            if (bouquet) {
                $.get(getPath(bouquet.uri, ''), function (data) {
                    DisplayChannels(bouquet.name, data);
                });
            }
            else {                
                $.get(getPath(uri.getServices,"4097:7:0:6:0:0:0:0:0:0:"), function (data) {
                    var bouquets = getBouquets(data);
                    var bouquet = getSelectedBouquet(bouquets);
                    $.get(getPath(uri.getServices,bouquet.command), function (data) {
                        DisplayChannels(bouquet.name, data);
                    });
                });
            }
        }
        catch (err) { alert(err.message); }
    });
    
    $('#settings').bind('pagebeforeshow', function (event, data) {
        try {
            settingID = undefined;
            DisplaySettings();
        }
        catch (err) { alert(err.message); }
    });

    $('#profiles').bind('pagebeforeshow', function (event, data) {
        try {            
            DisplaySettingsItem();
        }
        catch (err) { alert(err.message); }
    });

    $('#epg').bind('pagebeforeshow', function (event, data) {
        try {
            //localStorage.setItem("username", "John");
            //var test = '<!DOCTYPE html><body><table><tr><td></td><tr></table></body></html>'
            //alert($('body', test).html());
            //window.localStorage.setItem("item_key", "value I am storing");
            //var data = localStorage.getItem("item_key");
            //alert(data);

            $.get(getPath(uri.currEPG, ''), function (data) {
                try {
                    $(data).find('tbody tr td:nth-child(2)').each(function () {
                        data = data.replace($(this).html(), '');
                    });
                    var content = data.split('<body>')[1].split('</body>')[0];
                    $('#epgContent').html(content);
                }
                catch (err) { alert(err.message) }
            });
        }
        catch (err) { alert(err.message); }
    });

    $('#confirmPage').bind('pagebeforeshow', function (event, data) {
        try {
            $('#profileName').text(settingID);
        }
        catch (err) { alert(err.message); }
    });

    $('#viewEPG').click(function (event) { $.mobile.changePage('index.html#epg'); });

    $('#rcPower').click(function (event) { $.get(getPathRC(RemoteControl.power)); });
    $('#rcOK').click(function (event) { $.get(getPathRC(RemoteControl.ok)); });
    $('#rcCancel').click(function (event) { $.get(getPathRC(RemoteControl.cancel)); });
    $('#rcInfo').click(function (event) { $.get(getPathRC(RemoteControl.info)); });
    $('#rcOKcnl').click(function (event) {
        var channel = $('#number-1').val();
        for (var i = 0; i < channel.length; i++) {
            $.get(getPathRC(RemoteControl[channel[i]]));
        }
        $.get(getPathRC(RemoteControl.ok));
        $('#number-1').val('')
    });
    $('#rcVolumeUp').click(function (event) { $.get(getPathRC(RemoteControl.volumeUp)); });
    $('#rcVolumeDown').click(function (event) { $.get(getPathRC(RemoteControl.volumeDown)); });
    $('#rcMute').click(function (event) { $.get(getPathRC(RemoteControl.mute)); });
    $('#rcDream').click(function (event) {$.get(getPathRC(RemoteControl.dream));});
    $('#rcAudio').click(function (event) {$.get(getPathRC(RemoteControl.audio));});
    $('#rcVideo').click(function (event) {$.get(getPathRC(RemoteControl.video));});
    $('#rcNavUp').click(function (event) {$.get(getPathRC(RemoteControl.up));});
    $('#rcNavDown').click(function (event) {$.get(getPathRC(RemoteControl.down));});
    $('#rcNavLeft').click(function (event) {$.get(getPathRC(RemoteControl.left));});
    $('#rcNavRight').click(function (event) {$.get(getPathRC(RemoteControl.right));});
    $('#rcRed').click(function (event) {$.get(getPathRC(RemoteControl.red));});
    $('#rcGreen').click(function (event) {$.get(getPathRC(RemoteControl.green));});
    $('#rcYellow').click(function (event) {$.get(getPathRC(RemoteControl.yellow));});
    $('#rcBlue').click(function (event) {$.get(getPathRC(RemoteControl.blue));});
    $('#rcTV').click(function (event) {$.get(getPathRC(RemoteControl.tv));});
    $('#rcRadio').click(function (event) {$.get(getPathRC(RemoteControl.radio));});
    $('#rcText').click(function (event) {$.get(getPathRC(RemoteControl.text));});
    $('#rcNavHelp').click(function (event) { $.get(getPathRC(RemoteControl.help)); });

    $('#rcOne').click(function (event) { $.get(getPathRC(RemoteControl[1])); });
    $('#rcTwo').click(function (event) { $.get(getPathRC(RemoteControl[2])); });
    $('#rcThree').click(function (event) { $.get(getPathRC(RemoteControl[3])); });
    $('#rcFour').click(function (event) { $.get(getPathRC(RemoteControl[4])); });
    $('#rcFive').click(function (event) { $.get(getPathRC(RemoteControl[5])); });
    $('#rcSix').click(function (event) { $.get(getPathRC(RemoteControl[6])); });
    $('#rcSeven').click(function (event) { $.get(getPathRC(RemoteControl[7])); });
    $('#rcEight').click(function (event) { $.get(getPathRC(RemoteControl[8])); });
    $('#rcNine').click(function (event) { $.get(getPathRC(RemoteControl[9])); });
    $('#rcZero').click(function (event) { $.get(getPathRC(RemoteControl[0])); });

    $('#settingsSave').click(function (event) { SaveSettings(); });
    $('#addReceiver').click(function (event) { $.mobile.changePage('#profiles'); });

    $('#ipAddress').click(function () { GetIpAddress(); });
    $('.noConnection').click(function () { LaunchWiFi(); });

    $('#confirmPage_yes').click(function () {SettingsHelper.DeleteSettings(settingID); $.mobile.changePage('#settings');});
    $('#confirmPage_no').click(function () { $.mobile.changePage('#settings'); });

});

function onPause() {
    //console.log('pause');
}

function onResume() {
    console.log('resume');
    CheckConnection();
}

function LaunchWiFi() {
    cordova.exec(
        function (success) { consol.log('wifi screen loaded successfully') },
        function (fail) { alert('wifi screen failed to load') },
        'WPNative', 'LaunchWiFi', []);
};

function GetIpAddress() {
    cordova.exec(
        function (success) { DisplayIP(success); },
        function (fail) { DisplayIP(fail); },
        'WPNative', 'GetIpAddress', []);
};

function DisplayIP(msg)
{
    if (msg.length > 0) {
        alert("Your IP address is the following:\n\r" + msg + "\n\rMake sure you change the last part before saving.")
        $('#host').val(msg);
    }
    else {
        alert("IP address could not be resolved.\n\rMake sure you are connected on the network and try again.")
    }
}

function CheckConnection() {
    var networkState = navigator.network.connection.type;

    var states = {};
    states[Connection.UNKNOWN] = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI] = 'WiFi connection';
    states[Connection.CELL_2G] = 'Cell 2G connection';
    states[Connection.CELL_3G] = 'Cell 3G connection';
    states[Connection.CELL_4G] = 'Cell 4G connection';
    states[Connection.NONE] = 'No network connection';

    //## check if wifi is available
    if (states[networkState] != states[Connection.WIFI]) {        

        setTimeout(CheckConnection, 500);
        if(connAttempts  >= 3)
            $('.noConnection').show();

        console.log('connAttempts ' + connAttempts);
        connAttempts++;
        //if(connAttempts>=3)
        //alert("You dont have a WIFI connection available.\nThe communication might not be successful.\nCheck your connection and try again.");
    }
    else {
        $('.noConnection').hide();
        connAttempts = 0;
        console.log('connAttempts ' + connAttempts);
    }

    //## check if there is communication with dreambox
    $.get(getPath(uri.pmt, ''), function (current) {

    });

    //alert('Connection type: ' + states[networkState]);
}

function SaveSettings() {
    
    var settingsItem = new Settings();

    settingsItem.isActive = $('#activeProfile').val();
    settingsItem.receiver = $('#receiver').val();
    settingsItem.host = $('#host').val();
    settingsItem.user = $('#user').val();
    settingsItem.password = $('#password').val();
    settingsItem.port = $('#port').val();
    settingsItem.params = $('#params').val();
    settingsItem.ssl = $('#ssl').val();

    //console.log('host ' + SettingsHelper.SettingsList().length);
    if (!SettingsHelper.isValid(settingsItem, settingID))
        return;

    var request = $.get(getPathWithSettings(settingsItem, uri.currService,''));
    $.mobile.loading("show", {
        textVisible: $.mobile.loader.prototype.options.textVisible,
        html: '<div style="width:100%;opacity:.8;">' +
                    '<div style="margin:0 0;padding:30px 0;background-color:#000;text-align:center;opacity:none;">' +
                    '<div>Saving settings...</div><div>Please wait</div>' +
                '</div></div>'
    });

    request.success(function (result) {
        $.mobile.loading("show");
        //## success ##//
        var settingsList = SettingsHelper.SettingsList();
        if (settingID && settingID.length > 0) {
            for (var i = 0; i < settingsList.length; i++) {
                if (settingsList[i].receiver == settingID) {
                    settingsList[i] = settingsItem;

                    break;
                }
            }
        }
        else
            settingsList.push(settingsItem);

        //settingsList = [];
        SettingsHelper.SetupSettings(settingsList);
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccessW, fail);
    });

    request.error(function (jqXHR, textStatus, errorThrown) {
        $.mobile.loading("hide");
        alert('Error contacting the device. Please review your connection or settings')
        if (textStatus == 'timeout')
            console.log('The server is not responding');

        if (textStatus == 'error')
            console.log(errorThrown);
    });
};

function DisplaySettings() {
    try {
        setupSettings();
    }
    catch (err) { alert(err.message) }
};

function DisplaySettingsItem() {
    try {
        setupSettingsItem();
    }
    catch (err) { alert(err.message) }
};

function setupSettings() {
    $('#settingsList li').remove();

    $('#settingsList').append($('<li/>', { 'data-role': "list-divider", text: 'Settings' }));

    var activeProfile = SettingsHelper.GetSettingsActive();
    var settings = SettingsHelper.SettingsList();

    if (activeProfile.length == 0) {
        $('#noActive').show();
    }
    else {
        $('#noActive').hide();
    }

    for (var i = 0; i < settings.length; i++) {
        $('#settingsList').append($('<li/>', {})
                    .append($('<div/>',{
                        'href': '#profiles',
                        css: {float:'left', 'background-color':settings[i].isActive == 'on' ? '#0099FF':'none', padding:'2px', width:'80%'},
                        'param': settings[i].receiver,
                        'data-transition': 'slide',
                        'data-nav': 'test',
                        'class': 'settingItem',
                    }).append($('<h2/>', {
                        'text': settings[i].receiver,
                    })).append($('<p/>', {
                        text: 'IP: ' + settings[i].host + (settings[i].port.length==0 ? '' : ':' + settings[i].port)
                    }))//end <p/>
                        )/*end first div */
                        .append($('<div/>', { 
                            text: '✘',
                            'class': 'settingDelete',
                            'param': settings[i].receiver,
                        }))// end second div
                        .append($('<div/>', { css: { clear: 'both' }}))
        ); //end bouquetsList
    }

    $("#settingsList").listview("refresh");

    $("html, body").animate({ scrollTop: 0 }, "slow");

    $("#settingsList li .settingItem").click(function (event) {
        try {
            //event.preventDefault();
                
            settingID = $(this).attr('param');
            var htmlURI = $(this).attr('href');
            $.mobile.changePage(htmlURI);
        }
        catch (err) { alert(err.message); };
    });

    $("#settingsList li .settingDelete").click(function (event) {
        settingID = $(this).attr('param');
        $.mobile.changePage('#confirmPage');
    });
}

function setupSettingsItem() {

    var settingsItem = new Settings();

    var query = SQLike.q(
    {
        Select: ['*'],
        From: SettingsHelper.SettingsList(),
        Where: function(){return this.receiver == settingID}
    });
    //the screen is for edit exisitng settings
    if (query.length > 0) {
        settingsItem = query[0];
    }

    //## apply control values ##//
    $('#activeProfile').val(settingsItem.isActive).slider("refresh");
    $('#receiver').val(settingsItem.receiver);
    $('#host').val(settingsItem.host);
    $('#user').val(settingsItem.user);
    $('#password').val(settingsItem.password);
    $('#port').val(settingsItem.port);
    $('#params').val(settingsItem.params);
    $('#ssl').val(settingsItem.ssl);

    //## apply validation values ##//
    $('#activeProfileValidate').text('');
    $('#receiverValidate').text('');
    $('#hostValidate').text('');
    $('#userValidate').text('');
    $('#passwordValidate').text('');
    $('#portValidate').text('');
    $('#paramsValidate').text('');
}

function DisplayBouquets(data)
{
    try{        
        var allBouquets = getBouquets(data);
        setupBouquets(allBouquets);
    }
    catch (err) { alert(err.message)}
}

function setupBouquets(data)
{
    $('#bouquetsList li').remove();
    $('#chnlList li').remove();

    $('#bouquetsList').append($('<li/>', {'data-role': "list-divider", text:'Bouquets' }));

    for (var i = 0; i < data.length; i++) {

        $('#bouquetsList').append($('<li/>', {

            /*css:{ 'background-color': data[i].selected ? "#369":"none"},'data-role': "list-divider"*/
        })
                    .append($('<a/>', { 
                        'href': uri.getServices + data[i].command,
                        'data-transition': 'slide',
                        'text': data[i].name,
                        'data-nav':'test',
                    })//end <a/>
                        .append($('<img/>', {
                            'src': "Images/empty.png" ,
                            'class': "ui-li-icon"
                        }))//end <a/>                        
        )); //end bouquetsList
    }

    $("#bouquetsList").listview("refresh");

    $("html, body").animate({ scrollTop: 0 }, "slow");

    $("#bouquetsList li a").click(function (event) {
        try {
            event.preventDefault();

            var bName = $(this).text();
            var htmlURI = $(this).attr('href');
            bouquet = { name: bName, uri: htmlURI };
            $.mobile.changePage('index.html#channels');
        }
        catch (err) { alert(err.message); };
    });
}

function DisplayChannels(groupName, data) {
    try {
        var channels = [];
        var lines = data.split('\n');
        channels = getChannels(groupName, lines);        
        setupChannels(channels);
    }
    catch (err) { alert(err.message) }
}

function setupChannels(data) {

    $('#chnlList li').remove();

    $('#chnlList').append($('<li/>', { 'data-role': "list-divider", text: 'Bouquet: ' + data.group }));

    for (var i = 0; i < data.channels.length; i++) {
        $('#chnlList').append($('<li/>', {
            /*css: { 'background-color': data.channels[i].selected ? "#369" : "none" },
            'data-role': "list-divider"*/
            //'data-theme': 'c',
                    })
                    .append($('<a/>', {
                        id: data.channels[i].selected ? 'selectItemLink' : '',
                        'class': data.channels[i].selected ? 'ui-btn-up-b' : 'ui-btn-up-c',
                        'class': data.channels[i].selected ? 'ui-btn-up-b' : 'ui-btn-hover-c',
                        'data-theme': data.channels[i].selected ? 'b' : 'c',
                        'data-transition': 'slide',
                        'href': getPath(uri.zapToPath, data.channels[i].command),
                        'text': data.channels[i].name,
                        css: { 'color': data.channels[i].selected ? '#006699' : 'none', 'font-weight': data.channels[i].selected ? 'bold' : 'normal' }
                    })//end <a/>
                        .append($('<div/>', {
                            //'src': "Images/empty.png",
                            //'class': "ui-li-icon",
                            text: data.channels[i].selected ? '!' : '',
                            css: { color: '#fff','background-color': data.channels[i].selected ? '#006699' :'#999', float:'left', width:'32px', height:'32px', 'margin-right': '5px','text-align':'center'},
                        }))//end <a/>px'
        )); //end bouquetsList
    }

    $("#chnlList").listview("refresh");
    $("html, body").animate({ scrollTop: 0 }, "slow");
    
    //alert($("#selectItemLink").attr('class'));
    //$("#selectItemLink").click();
    //$("#selectItemLink").attr("data-theme", "b").removeClass("ui-btn-up-c").removeClass('ui-btn-hover-c').addClass("ui-btn-up-b").addClass('ui-btn-hover-b');
    

    $('#chnlList li a').bind('click', function () {

        $('#chnlList li a div').css('background-color', '#999').text('');
        $(this).find('div').css('background-color', '#069').text('!');

        $('#chnlList li a div').removeClass("selected");
        $(this).find('div').addClass("selected");

        $('#chnlList li a').attr("data-theme", "c").css('color', '#fff').css('font-weight', 'normal').removeClass("ui-btn-up-b").removeClass('ui-btn-hover-b').addClass("ui-btn-up-c").addClass('ui-btn-hover-c');
        $(this).attr("data-theme", "b").css('color', '#069').css('font-weight', 'bold').addClass('ui-link-inherit').removeClass("ui-btn-up-c").removeClass('ui-btn-hover-c').addClass("ui-btn-up-b").addClass('ui-btn-hover-b');
    });

    //window.scrollTo(0, 0);
    $('#chnlList li a div').click(function (event) {
        if ($(this).hasClass('selected')) {
            $("#chnlList li a").attr('href', '');
            $.mobile.changePage('index.html#epg');            
        }
    });

    $("#chnlList li a").click(function (event) {
        try {
            event.preventDefault();

            var htmlURI = $(this).attr('href');
            $.get(htmlURI);

        }
        catch (err) { alert(err.message); };
    });

}

function getBouquets(data) {
    var bouquets = [];
    var lines = data.split('\n');

    for (var i = 0; i < lines.length - 1; i++) {
        var item = lines[i].split(';');
        bouquets.push({ command: item[0], name: item[1], selected: item[2] == 'selected' ? true : false });
    }
    return bouquets;
}

function getChannels(groupName, list) {
    var result;
    var chnls = [];
    var selected = false;
    var item;

    for (var i = 0; i < list.length - 1; i++) {
        item = list[i].split(';');
        selected = false;
        if (item[0] == currChannel) {
            selected = true;
        }

        chnls.push({ command: item[0], name: item[1], service: item[2], other: item[3], selected: selected });
    }

    result = { group: groupName, channels: chnls };
    return result;
}

function getAllServices(current, list) {
    var result;
    var services = [];
    var items = list.split('\n');
    var selected = false;
    
    for (var i = 0; i < items.length - 1; i++) {
        var item = items[i].split(';');
        if (item[0] == current)
            selected = true;

        services.push({ command: item[0], name: item[1], provider: item[2], other: item[3], selected: selected });
    }

    allServices = services;
    
    result = services;
    
    return result;
}

function getSelectedBouquet(bouquets) {
    for (var i = 0; i < bouquets.length; i++)
    {
        if (bouquets[i].selected == true)
            return bouquets[i];
    }
};

function removeTags(tag, source)
    {
        var result;
        var t1 = content.split('<' + tag);
    }